TomatoBreak = @TomatoBreak
$ = jQuery

Task = TomatoBreak.Task

refreshListView = (list) ->

    list.listview 'destroy' if list.jqmData 'listview'
    list.listview inset: true

class TasksController extends Spine.Controller

    @elements:
        '.list':        'list'
        '.template':    'template'

    constructor: ->

        super

        Task.bind 'create', @created
        Task.bind 'update', @updated
        Task.bind 'destroy', @removed
        Task.bind 'refresh', @render

    activate: -> Task.fetch()

    reset: ->

    created: (task) =>

        @list.append (@template.tmpl task)
        refreshListView @list

    updated: (task) =>

        ($ "li[data-taskId=#{task.id}]", @list).replaceWith @template.tmpl task
        refreshListView @list

    removed: (task) =>

        ($ "li[data-taskId=#{task.id}]", @list).remove()
        refreshListView @list

    render: =>

        @list.empty()
        @list.append (@template.tmpl task) for task in Task.all()
        refreshListView @list

TomatoBreak.TasksController = TasksController